/**
 * SaveScoreScene.m
 * 
 * Revision History: 
 *
 * Date     Author       Version   Changes
 * ======== ============ ========= ================================================================
 * 03/25/10 Robin Mahony     2.0       Initial version.
 *								   
 * ======== ============ ========= ================================================================
 *
 */

#import "SaveScoreScene.h"
#import <SystemConfiguration/SystemConfiguration.h>
#include <netdb.h>

@implementation SaveScoreScene
/* This method initializes a Sprite object, which loads the background image. Then it sets the 
 Sprite's on-screen location to the middle of the screen. Finally, it adds the background sprite 
 to the scene and then proceed to instantiate the GameLogicLayer class and add it to the scene.  */
- (id) init
{
	
    self = [super init];
    
	if (self != nil) 
	{
		Sprite *bg = [Sprite spriteWithFile:@"pleaseenternameBackground.png"];
		[bg setPosition:ccp (160, 240) ];
		[self addChild:bg z:0];
		
		/* Set the depth ordering to 1, so everything will be on top of this background layer  */
        Layer *layer = [SaveScoreLayer node];
		[self addChild:layer z:1];
    }
    return self;
}


/* This method removes all objects added to the scene, indicating you want Cocos2D to “clean up” by 
 releasing the objects as well, and then you must call the dealloc method of the superclass  */
- (void) dealloc 
{
	[self removeAllChildrenWithCleanup:YES];
	[super dealloc];
}


@end

@implementation SaveScoreLayer
-(id) init
{
    self = [super init];
    isTouchEnabled = YES;
	
	/* Load all the currently saved scores and their corresponding names.  */
	scoreList[0] = [[NSUserDefaults standardUserDefaults]integerForKey:@"score1Key"];
	scoreList[1] = [[NSUserDefaults standardUserDefaults]integerForKey:@"score2Key"];
	scoreList[2] = [[NSUserDefaults standardUserDefaults]integerForKey:@"score3Key"];
	scoreList[3] = [[NSUserDefaults standardUserDefaults]integerForKey:@"score4Key"];
	scoreList[4] = [[NSUserDefaults standardUserDefaults]integerForKey:@"score5Key"];
		
	nameList[0] = [[NSUserDefaults standardUserDefaults]stringForKey:@"string1Key"];
	nameList[1] = [[NSUserDefaults standardUserDefaults]stringForKey:@"string2Key"];
	nameList[2] = [[NSUserDefaults standardUserDefaults]stringForKey:@"string3Key"];
	nameList[3] = [[NSUserDefaults standardUserDefaults]stringForKey:@"string4Key"];
	nameList[4] = [[NSUserDefaults standardUserDefaults]stringForKey:@"string5Key"];
	
	/* This line retrieves the score from the most recently played game.  */
	score = [[NSUserDefaults standardUserDefaults]integerForKey:@"tempScore"];
	
	
	NSLog(@"1.  %@  %d",nameList[0],scoreList[0]);
	NSLog(@"2.  %@  %d",nameList[1],scoreList[1]);
	NSLog(@"3.  %@  %d",nameList[2],scoreList[2]);
	NSLog(@"4.  %@  %d",nameList[3],scoreList[3]);
	NSLog(@"5.  %@  %d",nameList[4],scoreList[4]);
	
	
	
	[self specifyStartLevel];
    return self;
}

-(void)specifyStartLevel 
{
    myText = [[UITextField alloc] initWithFrame:CGRectMake(60, 165, 200, 40)];
	[myText setBackgroundColor:[UIColor clearColor]];
	myText.borderStyle = UITextBorderStyleRoundedRect;
    myText.autocapitalizationType = UITextAutocapitalizationTypeWords;
    [myText setDelegate:self];
    [myText setText:@""];
    [myText setTextColor: [UIColor colorWithRed:0 green:0 blue:0 alpha:1.0]];
    [[[[Director sharedDirector] openGLView] window] addSubview:myText];
    [myText becomeFirstResponder];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField 
{
    [myText resignFirstResponder];
    return YES;
}

-(void)textFieldDidEndEditing: (UITextField *)textField 
{
    if(textField == myText) {
        [myText endEditing:YES];
        [myText removeFromSuperview];
		[self saveScore: myText.text];

    } 
	else 
	{
        NSLog(@"textField did not match myText");
    }
}

- (void) alertView: (UIAlertView *) alertView 
clickedButtonAtIndex: (NSInteger) buttonIndex 
{
	[[Director sharedDirector] replaceScene:[MenuScene node]];
}

/* This method use NSUserDefaults to save name and score locally.  */
- (void) saveScore:(NSString *)userName 
{
	NSLog(@"savescore function entered");
	
	UIAlertView *alert = nil;
	
	/* Save the user's score and name in the correct order in our local list.  */  
	if(score>scoreList[0])
	{
		scoreList[4] = scoreList[3];
		nameList[4] = nameList[3];
		scoreList[3] = scoreList[2];
		nameList[3] = nameList[2];
		scoreList[2] = scoreList[1];
		nameList[2] = nameList[1];
		scoreList[1] = scoreList[0];
		nameList[1] = nameList[0];
		scoreList[0] = score;
		nameList[0] = userName;
	}
	else if(score>scoreList[1])
	{
		scoreList[4] = scoreList[3];
		nameList[4] = nameList[3];
		scoreList[3] = scoreList[2];
		nameList[3] = nameList[2];
		scoreList[2] = scoreList[1];
		nameList[2] = nameList[1];
		scoreList[1] = score;
		nameList[1] = userName;
	}
	else if(score>scoreList[2])
	{
		scoreList[4] = scoreList[3];
		nameList[4] = nameList[3];
		scoreList[3] = scoreList[2];
		nameList[3] = nameList[2];
		scoreList[2] = score;
		nameList[2] = userName;
	}
	else if(score>scoreList[3])
	{
		scoreList[4] = scoreList[3];
		nameList[4] = nameList[3];
		scoreList[3] = score;
		nameList[3] = userName;
	}
	else if(score>scoreList[4])
	{
		scoreList[4] = score;
		nameList[4] = userName;	
	}
	
		
	// Temporary name; to be replaced with username input function later.  
	NSUserDefaults *stringDefault = [NSUserDefaults standardUserDefaults];
	[stringDefault setObject: nameList[0] forKey:@"string1Key"];
	[stringDefault setObject: nameList[1] forKey:@"string2Key"];
	[stringDefault setObject: nameList[2] forKey:@"string3Key"];
	[stringDefault setObject: nameList[3] forKey:@"string4Key"];
	[stringDefault setObject: nameList[4] forKey:@"string5Key"];
	
	NSUserDefaults *intDefault = [NSUserDefaults standardUserDefaults];
	[intDefault setInteger:scoreList[0] forKey:@"score1Key"];
	[intDefault setInteger:scoreList[1] forKey:@"score2Key"];
	[intDefault setInteger:scoreList[2] forKey:@"score3Key"];
	[intDefault setInteger:scoreList[3] forKey:@"score4Key"];
	[intDefault setInteger:scoreList[4] forKey:@"score5Key"];
	
	[[NSUserDefaults standardUserDefaults] synchronize];
	alert = nil;
	alert = [[UIAlertView alloc] 
			 initWithTitle:[NSString stringWithFormat:@"Your score: %05d",  score]
			 message:@"Your score has been saved."
			 delegate:self 
			 cancelButtonTitle:@"Ok" 
			 otherButtonTitles:nil];
	[alert show];
	[alert release];
	
	
	
}



-(void) dealloc
{
	[super dealloc];
}
@end
